package com.cunshe.web.manage;

import com.cunshe.common.ResponseVO;
import com.cunshe.config.annotation.Login;
import com.cunshe.domain.Menu;
import com.cunshe.domain.Product;
import com.cunshe.entity.vo.ProductInsertVO;
import com.cunshe.entity.vo.ProductUpdateVO;
import com.cunshe.service.MenuService;
import com.cunshe.service.ProductService;
import com.cunshe.web.BaseController;
import com.sunkee.commons.utils.ConvertUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 产品
 * @author xiao
 */
@Api(tags = "产品")
@Login
@RestController
@RequestMapping(value = "/manage/product")
public class ProductController extends BaseController {

    @Autowired
    private ProductService productService;
    @Autowired
    private MenuService menuService;

    /** 新增 */
    @ApiOperation(value = "新增")
    @PostMapping(value = "insert")
    public ResponseVO insert(@RequestBody @Validated ProductInsertVO vo) {
        Product record = ConvertUtil.copyProperties(vo, Product.class);
        record.setCreateBy(getCurrentUser().getUsername());
        productService.insert(record, vo.getImages());
        return ResponseVO.success();
    }

    /** 删除 */
    @ApiOperation(value = "删除")
    @PostMapping(value = "delete")
    public ResponseVO delete(@RequestParam("id") Long id) {
        productService.delete(id);
        return ResponseVO.success();
    }

    /** 修改 */
    @ApiOperation(value = "修改")
    @PostMapping(value = "update")
    public ResponseVO update(@RequestBody @Validated ProductUpdateVO vo) {
        Product record = ConvertUtil.copyProperties(vo, Product.class);
        record.setUpdateBy(getCurrentUser().getUsername());
        productService.update(record, vo.getImages());
        return ResponseVO.success();
    }

    /** 查询列表 */
    @ApiOperation(value = "查询列表")
    @PostMapping(value = "list")
    public ResponseVO list(Product record) {
        List<Product> list = productService.list(record);
        List<Menu> menus = menuService.all();
        for (Product product : list) {
            String category1 = menus.stream().filter(var -> String.valueOf(var.getId()).equals(product.getCategory1())).findFirst()
                    .map(Menu::getTitle)
                    .orElse("");
            product.setCategory1Name(category1);

            String category2 = menus.stream().filter(var -> String.valueOf(var.getId()).equals(product.getCategory2())).findFirst()
                    .map(Menu::getTitle)
                    .orElse("");
            product.setCategory2Name(category2);
        }

        return ResponseVO.success(list);
    }

}